package com.tencent.sr.iris.basic.saas.common.utils;

import com.tencent.sr.rmall.common.exception.code.ErrorCode;
import com.tencent.sr.rmall.common.exception.retail.TRetailBizException;
import java.util.function.Predicate;
import java.util.function.Supplier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * @author acewang
 * @create 2020-11-06 4:37 下午
 **/
@Slf4j
public class CheckerUtil {

    /**
     * check 不为空，ObjectUtils.isEmpty 判断
     *
     * @param ref
     * @param e
     * @param <T>
     * @return
     */
    public static <T> T checkNotNull(T ref, ErrorCode e) {
        if (ObjectUtils.isEmpty(ref)) {
            log.warn("null check fail, errorCode={}, desc={}", e.getCode(), e.getDescription());
            throw new TRetailBizException(e.getCode(), e.getDescription());
        }
        return ref;
    }

    /**
     * check 表达式
     *
     * @param expression
     * @param e
     */
    public static void checkExpression(boolean expression, ErrorCode e) {
        if (!expression) {
            throw new TRetailBizException(e.getCode(), e.getDescription());
        }
    }

    /**
     * @param predicate
     * @param supplier 参数提供方
     * @param <T>
     */
    public static <T> void check(Predicate<T> predicate, Supplier<T> supplier, ErrorCode e) {
        //check 入参
        CheckerUtil.checkNotNull(predicate, e);
        CheckerUtil.checkNotNull(supplier, e);
        //参数提供方，获取校验参数
        T value = supplier.get();
        CheckerUtil.checkNotNull(value, e);
        //校验
        if (!predicate.test(value)) {
            log.warn("predicate check fail value={}, errorCode={}", value, e.getCode());
            throw new TRetailBizException(e.getCode(), e.getDescription());
        }
    }
}